import Timer from "./Timer.js";
import Util from "./Util.js";
import Config from "./Config.js";
import {AudioWrap} from "./interface.js";
import {Spirit} from "./main.js";

let canvas
const Map = function () {

  let map = Config.map, ctx, spirits = [];

  let init = function () {

    spirits = Array.prototype.slice.call(arguments, 0);

    canvas = document.body.appendChild(document.createElement('canvas'));

    canvas.style.position = 'absolute';

    canvas.style.zIndex = 10001;

    Map.width = canvas.width = 900 || map.windowWidth;
    Map.height = canvas.height = 490 || map.height;

    ctx = canvas.getContext('2d');

    Timer.push(frames);

    setTimeout(function () {
      let audio = new AudioWrap()

      audio.loop();

      audio.play('sound/china.mp3');
    }, 100)

    return ctx;
  }


  let clear = function () {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  }

  let frames = function () {
    clear();
  }


  let getMaxX = function () {
    return canvas.width;
  }

  return {
    init: init,
    getMaxX: getMaxX
  }
}()

let bg, ft1, ft
const createBackground = () => {
  bg = document.createElement('div');
  document.body.appendChild(bg);
  ft1 = document.createElement('img');
  ft = document.createElement('img');
  bg.appendChild(ft1);
  bg.appendChild(ft);

  bg.style.position = 'absolute';
  bg.style.left = 0;
  bg.style.top = 0;
  bg.style.width = '910px';
  bg.style.height = '490px';
  bg.style.overflow = 'hidden';
  bg.style.border = '10px ridge #EEE';

  ft1.style.position = 'absolute';
  ft1.width = 1400;
  ft1.height = 400;
  ft1.src = Util.imgObj[Config.map.bgBehind].obj.src;

  ft.style.position = 'absolute';
  ft.width = 1400;
  ft.height = 490;
  ft.src = Util.imgObj[Config.map.bgFront].obj.src;

  let f_left = 250;
  bg.scrollLeft = f_left;
}

setTimeout(() => createBackground(), 2000)

class Stage {
  /**
   * @type {Spirit}
   */
  me
  old_scrollLeft
  /**
   * @type {boolean|number}
   */
  scrolling = false
  dis = 0

  constructor(me) {
    this.me = me
  }
  startMark() {
    this.old_scrollLeft = bg.scrollLeft
  }
  stop() {
    this.scrolling = false
  }
  scroll(dir) {
    const dis = dir === 'left' ? -3 : 3;
    this.old_scrollLeft = bg.scrollLeft;
    bg.scrollLeft += dis;
    if (this.old_scrollLeft !== bg.scrollLeft) {
      this.scrolling = dis;
    } else {
      this.stop();
    }
    this.dis = dis
  }
  pushEnemy() {
    if (this.old_scrollLeft === bg.scrollLeft || !this.scrolling) {
      return;
    }
    this.me.enemy.left = this.me.enemy.left - this.dis;
  }
  isScrolling() {
    return this.scrolling
  }
}

export {Map, Stage, createBackground}




































